package com.ali.order.converter;

import com.ali.order.dto.OrderDTO;
import com.ali.order.entity.OrderDetail;
import com.ali.order.enums.ResultEnum;
import com.ali.order.exception.OrderException;
import com.ali.order.form.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName OrderForm2OrderDTO
 * @Description TODO
 * @Author Alistair.Chow
 * @date 2018/12/21 16:42
 * @Version 1.0
 */
public class OrderForm2OrderDTOConverter {
    public static OrderDTO convert(OrderForm orderForm){
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetailList = new ArrayList<>();

        Gson gson = new Gson();

        try {
            orderDetailList = gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>() {
                    }.getType());
        }
        catch (Exception e){
            throw new OrderException(ResultEnum.PARAM_CODE);
        }

        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}
